import { useMorghulisRequest } from "./request";
import { inject } from "vue";
import type { ChannelActivator, MorghulisChannel, MorghulisChannels } from "../types/channel.types";
import { $channel } from "../tools/sockets";

export function useMorghulisChannel(baseURL: string) {
    const { getRequest } = useMorghulisRequest(baseURL);
    const http = getRequest();
    
    // 获取sockets实例
    const channelInstance = $channel({ baseURL });
    const { sockets } = channelInstance;
    const { channels, status, open } = sockets;
    
    function register(
        handler: string,
        channel: MorghulisChannel,
        auth: boolean = false,
        url?: string
    ): ChannelActivator {
        channels[handler] = channel;
        const request = getRequest(auth);
        url = url || `socket/${handler}`;
        return (body) => request.post(url, body);
    }

    return {
        http,
        open,
        status,
        register
    };
}